package com.wxx.多数元素;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: Jetwang
 * @date: 2022/4/5 21:31
 * @description: Solution 多数元素
 * @version: 1.0
 */
public class Solution {
    public static int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>(16);
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                map.put(nums[i], map.get(nums[i]) + 1);
            } else {
                map.put(nums[i], 1);
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > nums.length / 2) {
                return entry.getKey();
            }
        }
        return -1;
    }

    /**
     * 第二种解法: 对拼消耗法
     * @param nums
     * @return
     */
    public static int majorityElement02(int[] nums) {
        int res = 0;
        int count = 0;
        for (int num : nums) {
            res = count == 0 ? num : res;
            count = (res == num ? ++count : --count);
        }
        return res;
    }

    public static void main(String[] args) {
        int num01 = majorityElement(new int[]{3, 2, 3});
        System.out.println(num01);
        int num02 = majorityElement(new int[]{2,2,1,1,1,2,2});
        System.out.println(num02);

        int num03 = majorityElement(new int[]{3, 2, 3});
        System.out.println(num03);
        int num04 = majorityElement(new int[]{2,2,1,1,1,2,2});
        System.out.println(num04);
    }
}
